package com.csdj.t309springboot.config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class RedisService2 extends MessageListenerAdapter {

    private Logger log = LoggerFactory.getLogger("test");
    @Resource
    private RedisTemplate<String,Object> objectRedisTemplate;

//    public void setString(String key,String value,int second){
//        objectRedisTemplate.opsForValue().set();
//    }



    public void setObject(String key,Object obj){
        objectRedisTemplate.opsForValue().set(key,obj);
    }

    public <T> T getObject(String key){
        Object o = objectRedisTemplate.opsForValue().get(key);
        return (T)o;
    }

    public <T extends Object> T getObject(String key,Class clazz){
        Object o = objectRedisTemplate.opsForValue().get(key);
        if(o == null)return null;
        if(clazz.isInstance(o))
            if(o.getClass().getName().equalsIgnoreCase(clazz.getName())){
                return (T)o;
            }
        log.error("{}的值不是{}的实例",key,clazz.getName());
        return null;
    }

    /**
     * redis订阅消息处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
//        super.onMessage(message, pattern);
//        log.info("channel:{} message:{}",new String(message.getChannel()),new String(message.getBody()));
    }
}
